package cn.andrewlu.weexshell.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import cn.andrewlu.weexshell.utils.ViewIdGenerator;

/**
 * Created by andrewlu on 2017/6/4.
 * 所有Fragment的基类.提供一些基础方法.
 */

public abstract class RootFragment extends Fragment {
    private List<WeakReference<ILifeCycleChangeListener>> mLifeCycleChangeListeners = new ArrayList<>();

    public void addLifeCycleListener(ILifeCycleChangeListener listener) {
        mLifeCycleChangeListeners.add(new WeakReference<ILifeCycleChangeListener>(listener));
    }

    @Nullable
    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        FrameLayout root = new FrameLayout(getContext());
        root.setId(ViewIdGenerator.id());
        return root;
    }

    @Override
    public void onStart() {
        super.onStart();
        for (WeakReference<ILifeCycleChangeListener> listener : mLifeCycleChangeListeners) {
            ILifeCycleChangeListener l = listener.get();
            if (l != null) {
                l.onActivityStart();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        for (WeakReference<ILifeCycleChangeListener> listener : mLifeCycleChangeListeners) {
            ILifeCycleChangeListener l = listener.get();
            if (l != null) {
                l.onActivityResume();
            }
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        for (WeakReference<ILifeCycleChangeListener> listener : mLifeCycleChangeListeners) {
            ILifeCycleChangeListener l = listener.get();
            if (l != null) {
                l.onActivityStop();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        for (WeakReference<ILifeCycleChangeListener> listener : mLifeCycleChangeListeners) {
            ILifeCycleChangeListener l = listener.get();
            if (l != null) {
                l.onActivityPause();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        for (WeakReference<ILifeCycleChangeListener> listener : mLifeCycleChangeListeners) {
            ILifeCycleChangeListener l = listener.get();
            if (l != null) {
                l.onActivityDestroy();
            }
        }
    }
}
